localize取得翻譯內容:ng extract-i18n 取得翻譯內容,並生成對應語言的 .xlf 或其他格式的翻譯文件(如 messages.fr.xlf)。
設定 Angular CLI 的 angular.json:修改 angular.json 檔案中的 i18n 設定,來定義多個語言。這些設定將告訴編譯器應該在哪裡找到不同語言的翻譯檔案。
angular.json 中的語言選項在 angular.json 中,你可以為專案定義語系和對應的翻譯檔案。
{
"projects": {
"angular.io-example": {
...
"i18n": {
"sourceLocale": "en-US",
"locales": {
"fr": {
"translation": "src/locale/messages.fr.xlf"
}
}
},
"architect": {
...
}
}
}
}
sourceLocale 定義應用程式中預設使用的語言。locales 是一個語言對應翻譯檔案的對應表。法語(fr)對應的翻譯檔案位於 src/locale/messages.fr.xlf。angular.json localize 選項來生成不同語系的應用程式版本:localize :true :為所有定義的語系生成版本["fr"]生成部分語系的版本 ,格式陣列false - 不生成本地化版本
範例:
{
"projects": {
"angular.io-example": {
...
"architect": {
"build": {
"options": {
"localize": true,
...
}
}
}
}
}
}
這樣做會在每個語系下生成一個版本的應用程式,且 HTML 的 lang 屬性也會自動設定為該語系。
使用命令行來生成多語系的應用程式。
在 angular.json 中設定了多語系,可以使用以下命令:
ng build --localize
只為法語(fr)定義
{
"projects": {
"angular.io-example": {
...
"architect": {
"build": {
"configurations": {
"fr": {
"localize": ["fr"]
}
}
},
"serve": {
"configurations": {
"fr": {
"buildTarget": "angular.io-example:build:development,fr"
}
}
}
}
}
}
}
ng serve --configuration=fr
ng build --configuration=production,fr
angular.json options.i18nMissingTranslation :errorwarningignore
範例(將警告等級設為 error):
{
"projects": {
"angular.io-example": {
...
"architect": {
"build": {
"options": {
"i18nMissingTranslation": "error"
}
}
}
}
}
}